package com.sansan.qiangji.utils;

import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
public class DateUtil {
    /**
     * 当前日期格式转换
     */
    public static Date nowDate(String dateFormat) {
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        Date date = new Date();
        String dateStr = format.format(date);
        try {
            date = format.parse(dateStr);
        } catch (ParseException e) {
            log.error("【编辑首检记录】日期转换异常 date={}", date);
            e.printStackTrace();
            throw new ServiceException(ResultEnum.DATE_FORMAT_ERROR);
        }
        return date;
    }

    /**
     * 当前日期格式转换
     */
    public static String nowString(String dateFormat) {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
        return sf.format(date);
    }


    /**
     * 日期格式转换date2String
     */
    public static String date2String(Date date ,String dateFormat) {
        SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
        return sf.format(date);
    }

    /**
     * 日期格式转换String2date
     */
    public static Date string2Date(String dateStr ,String dateFormat) {
        SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
        Date date = null;
        try {
            date = sf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    //日期加减
    public static Date dateAddNum(Date date,Integer num){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE,num);
        Date newDate = cal.getTime();
        return newDate;
    }

    //返回两天之间的日期集合
    public static List<String> dayBetweenTwoDate(String startTime, String endTime){
        // 返回的日期集合
        List<String> days = new ArrayList<>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }
}
